import { Injectable, OnModuleInit } from '@nestjs/common';
import { RoleService } from '../role/role.service';
import { PermissionService } from './permission.service';

/**
 * 权限初始化服务
 *
 * 在应用启动时自动执行，初始化系统角色和权限
 */
@Injectable()
export class PermissionInitService implements OnModuleInit {
  constructor(
    private readonly roleService: RoleService,
    private readonly permissionService: PermissionService,
  ) {}

  /**
   * 模块初始化时执行
   */
  async onModuleInit() {
    console.log('🔐 初始化权限系统...');
    await this.initPermissions();
    await this.initRoles();
    await this.assignPermissionsToRoles();
    console.log('✅ 权限系统初始化完成');
  }

  /**
   * 初始化权限
   */
  private async initPermissions() {
    const permissions = [
      // 商品权限
      {
        name: 'product:read',
        displayName: '查看商品',
        resource: 'product',
        action: 'read',
        description: '可以查看商品列表和详情',
      },
      {
        name: 'product:create',
        displayName: '创建商品',
        resource: 'product',
        action: 'create',
        description: '可以创建新商品',
      },
      {
        name: 'product:update',
        displayName: '更新商品',
        resource: 'product',
        action: 'update',
        description: '可以更新商品信息',
      },
      {
        name: 'product:delete',
        displayName: '删除商品',
        resource: 'product',
        action: 'delete',
        description: '可以删除商品',
      },

      // 订单权限
      {
        name: 'order:read',
        displayName: '查看订单',
        resource: 'order',
        action: 'read',
        description: '可以查看自己的订单',
      },
      {
        name: 'order:create',
        displayName: '创建订单',
        resource: 'order',
        action: 'create',
        description: '可以创建订单',
      },
      {
        name: 'order:cancel',
        displayName: '取消订单',
        resource: 'order',
        action: 'cancel',
        description: '可以取消自己的订单',
      },
      {
        name: 'order:manage',
        displayName: '管理订单',
        resource: 'order',
        action: 'manage',
        description: '可以管理所有订单',
      },

      // 用户权限
      {
        name: 'user:read',
        displayName: '查看用户',
        resource: 'user',
        action: 'read',
        description: '可以查看用户列表',
      },
      {
        name: 'user:update',
        displayName: '更新用户',
        resource: 'user',
        action: 'update',
        description: '可以更新用户信息',
      },
      {
        name: 'user:delete',
        displayName: '删除用户',
        resource: 'user',
        action: 'delete',
        description: '可以删除用户',
      },
      {
        name: 'user:manage',
        displayName: '管理用户',
        resource: 'user',
        action: 'manage',
        description: '可以管理所有用户',
      },

      // 下载权限
      {
        name: 'download:free',
        displayName: '免费下载',
        resource: 'download',
        action: 'free',
        description: '可以下载免费商品',
      },
      {
        name: 'download:paid',
        displayName: '付费下载',
        resource: 'download',
        action: 'paid',
        description: '可以下载已购买的商品',
      },
      {
        name: 'download:vip',
        displayName: 'VIP下载',
        resource: 'download',
        action: 'vip',
        description: '可以使用VIP配额下载',
      },
      {
        name: 'download:svip',
        displayName: 'SVIP下载',
        resource: 'download',
        action: 'svip',
        description: '可以使用SVIP配额下载',
      },
    ];

    await this.permissionService.createBatch(permissions);
  }

  /**
   * 初始化角色
   */
  private async initRoles() {
    const roles = [
      {
        name: 'user',
        displayName: '普通用户',
        description: '可以浏览商品、购买商品',
        level: 1,
        isSystem: true,
      },
      {
        name: 'vip',
        displayName: 'VIP会员',
        description: '享受8折优惠，每月3次免费下载',
        level: 2,
        isSystem: true,
      },
      {
        name: 'svip',
        displayName: 'SVIP会员',
        description: '享受6折优惠，每月10次免费下载',
        level: 3,
        isSystem: true,
      },
      {
        name: 'admin',
        displayName: '系统管理员',
        description: '拥有所有权限',
        level: 99,
        isSystem: true,
      },
    ];

    for (const roleDto of roles) {
      try {
        await this.roleService.create(roleDto);
      } catch (error) {
        // 角色已存在，跳过
      }
    }
  }

  /**
   * 为角色分配权限
   */
  private async assignPermissionsToRoles() {
    // 普通用户权限
    const userRole = await this.roleService.findByName('user');
    const userPermissions = await this.permissionService.findByNames([
      'product:read',
      'order:read',
      'order:create',
      'order:cancel',
      'download:free',
      'download:paid',
    ]);
    if (userRole && userPermissions.length > 0) {
      await this.roleService.assignPermissions(
        userRole.id,
        userPermissions.map((p) => p.id),
      );
    }

    // VIP权限（包含普通用户权限 + VIP特权）
    const vipRole = await this.roleService.findByName('vip');
    const vipPermissions = await this.permissionService.findByNames([
      'product:read',
      'order:read',
      'order:create',
      'order:cancel',
      'download:free',
      'download:paid',
      'download:vip',
    ]);
    if (vipRole && vipPermissions.length > 0) {
      await this.roleService.assignPermissions(
        vipRole.id,
        vipPermissions.map((p) => p.id),
      );
    }

    // SVIP权限（包含VIP权限 + SVIP特权）
    const svipRole = await this.roleService.findByName('svip');
    const svipPermissions = await this.permissionService.findByNames([
      'product:read',
      'order:read',
      'order:create',
      'order:cancel',
      'download:free',
      'download:paid',
      'download:vip',
      'download:svip',
    ]);
    if (svipRole && svipPermissions.length > 0) {
      await this.roleService.assignPermissions(
        svipRole.id,
        svipPermissions.map((p) => p.id),
      );
    }

    // 管理员拥有所有权限
    const adminRole = await this.roleService.findByName('admin');
    const allPermissions = await this.permissionService.findAll();
    if (adminRole && allPermissions.length > 0) {
      await this.roleService.assignPermissions(
        adminRole.id,
        allPermissions.map((p) => p.id),
      );
    }
  }
}
